<?php

namespace app\admin\controller\xmwms;

use app\common\controller\Backend;
use ba\Tree;

class Category extends Backend
{
     /**
      * @var \app\admin\model\xmwms\Category
      */
     protected object $model;

     protected Tree $tree;

     protected ?string $keyword;

     protected string|array $defaultSortField = 'weigh,desc';

     protected string|array $preExcludeFields = ['id', 'create_time', 'update_time'];

     protected string|array $quickSearchField = 'name';

     public function initialize(): void
     {
          parent::initialize();
          $this->model = new \app\admin\model\xmwms\Category;
          $this->tree = Tree::instance();
          $this->keyword = $this->request->request("quickSearch");
     }

     public function index(): void
     {
          if ($this->request->param('select')) {
               $this->select();
          }
          $status = $this->request->param('status');
          $where = [];
          if (isset($status)) {
               $where[] = ['status', '=', $status];
          }
          $this->success('', [
               'list' => $this->getCategory($where),
               'remark' => get_route_remark(),
          ]);
     }

     public function edit($id = null): void
     {
          $row = $this->model->find($id);
          if (!$row) {
               $this->error(__('Record not found'));
          }

          if ($this->request->isPost()) {
               parent::edit($id);
          }

          $this->success('', [
               'row' => $row
          ]);
     }


     public function select(): void
     {
          $isTree = $this->request->param('isTree');
          $data = $this->getCategory([['status', '=', '1']]);

          if ($isTree && !$this->keyword) {
               $data = $this->tree->assembleTree($this->tree->getTreeArray($data, 'name'));
          }
          $this->success('', [
               'options' => $data
          ]);
     }

     protected function getCategory($where = [])
     {
          if ($this->keyword) {
               $keyword = explode(' ', $this->keyword);
               foreach ($keyword as $item) {
                    $where[] = [$this->quickSearchField, 'like', '%' . $item . '%'];
               }
          }
          $data = $this->model->where($where)->order('weigh desc,id asc')->select()->toArray();
          return $this->tree->assembleChild($data);
     }
}
